package com.example.android.utils;

import android.util.Log;


import com.example.android.utils.api.BackApi;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FileUpload {
    public static void uploadImage(String realPath, StringBuilder url) {

        String path = realPath;
        String newPath = BitmapUtil.compressImage(path);//压缩
        File imageFile = new File(newPath);//将路径放到File集合里面去传到接口
        //加载图片到image中
        MediaType MEDIA_TYPE_PNG = MediaType.parse("multipart/form-data");
        RequestBody requestFile = RequestBody.create(MEDIA_TYPE_PNG, imageFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
        //图片上传请求
        NetUtil.INSTANCE.get(NetUtil.INSTANCE.getBaseUrlDev()).create(BackApi.class).uploadImage(body).enqueue(new Callback<BaseModel<String>>() {
            @Override
            public void onResponse(Call<BaseModel<String>> call, Response<BaseModel<String>> response) {
                Log.i("TAG", "onResponse: " + response.body().toString());
                if ((response.body() != null ? response.body().getCode() : null) == 200) {
                    Log.i("TAG", "onResponse: " + response.body().toString());
                    String newurl = response.body().getMsg();
                    url.append(newurl);
                    Log.i("TAG", "onResponse: " + newurl);
                }
            }

            @Override
            public void onFailure(Call<BaseModel<String>> call, Throwable t) {
                Log.i("TAG", "onFailure: " + t.getMessage());
            }
        });
    }

    /**
     * 封装后端头像上传接口
     *
     * @param realPath 本地图片真实路径
     */
    public static void uploadImageAvatar(String realPath) {
        String newPath = BitmapUtil.compressImage(realPath);//压缩
        File imageFile = new File(newPath);//将路径放到File集合里面去传到接口
        //加载图片到image中
        MediaType MEDIA_TYPE_PNG = MediaType.parse("multipart/form-data");
        RequestBody requestFile = RequestBody.create(MEDIA_TYPE_PNG, imageFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("avatarfile", imageFile.getName(), requestFile);
        //图片上传请求
        NetUtil.INSTANCE.get(NetUtil.INSTANCE.getBaseUrlDev()).create(BackApi.class).uploadAvatarBaseModelCall(body).enqueue(new Callback<BaseModel<Object>>() {
            @Override
            public void onResponse(Call<BaseModel<Object>> call, Response<BaseModel<Object>> response) {
                Log.i("TAG", "onResponse: " + response.body().toString());

            }

            @Override
            public void onFailure(Call<BaseModel<Object>> call, Throwable t) {
                Log.i("TAG", "onFailure: " + t.getMessage());
            }
        });
    }


}
